package fudan.se.project.security.filter;


import com.fasterxml.jackson.databind.ObjectMapper;
import fudan.se.project.config.ConferenceScheduleConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class ConferenceScheduleFilter extends OncePerRequestFilter {

    private final ObjectMapper mapper;
    private ConferenceScheduleConfig conferenceScheduleConfig;

    @Autowired
    public ConferenceScheduleFilter(ObjectMapper mapper, ConferenceScheduleConfig conferenceScheduleConfig) {
        this.mapper = mapper;
        this.conferenceScheduleConfig = conferenceScheduleConfig;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws IOException, ServletException {

        String uri = request.getRequestURI();

        if (!conferenceScheduleConfig.isRunning()) {
            filterChain.doFilter(request, response);
        } else if ("/login".equals(uri) ||
                "/register".equals(uri) ||
                "/update".equals(uri)) {
            filterChain.doFilter(request, response);
        } else {
            response.setStatus(503);
            Map<String, Object> json = new HashMap<>();
            json.put("message", "service not available, try later plz :)");

            response.setContentType(MediaType.APPLICATION_JSON_VALUE);

            mapper.writeValue(response.getWriter(), json);
        }


    }
}
